﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizCustomerRefund : CustBizObject
    {
        private CDmDjkCustomerRefund m_CDmDjkCustomerRefund = new CDmDjkCustomerRefund();
        private CDmDjkCustomerRefund oDmDjkCustomerRefund
        {
            get { return m_CDmDjkCustomerRefund; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizCustomerRefund()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkCustomerRefund.DJK_CUSTOMER_REFUND);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["CUSTOMER_REFUND_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }
        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpPageColumn objtem = new CBizShpPageColumn())
            //{
            //    DataSet ds = objtem.SelectByPageNo(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //} 
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowDeletedR(DataRow drw)
        {
            return true;
        }

        //public DataSet SelectByIds(string strIdS)
        //{
        //    CDbParmCollection parmCollection = new CDbParmCollection();
        //    parmCollection.Add(new CDbParm("strIdS", ParameterDirection.Input, EDbType.String, 36, strIdS.Replace("'", "").Replace(",", "','")));
        //    DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('@strIdS')");
        //    ds.Tables[0].TableName = this.TableName;
        //    return ds;
        //}

        /// <summary>
        /// 申请退款
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="expanation">退款说明</param>
        /// <param name="breachPerson">违约人 1代表地接客，2代表游客，默认为1</param>
        /// <returns></returns>
        public string ApplyRefund(string orderId, string expanation, int breachPerson = 1)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "申请退款失败，订单信息有误";
            }
            if (string.IsNullOrEmpty(expanation))
            {
                return "申请退款失败，退款说明不能为空";
            }

            CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo();

            DataSet dsOrder = objCBizOrdersInfo.GetOrderInfoById(orderId);

            if (dsOrder == null
                || dsOrder.Tables[0].Rows.Count <= 0)
            {
                return "申请退款失败，订单信息有误";
            }



            if ((OrderStatusEnum)dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] != OrderStatusEnum.PaiedAll
                && (OrderStatusEnum)dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] != OrderStatusEnum.RefundCanceled
                && (OrderStatusEnum)dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] != OrderStatusEnum.Refusal)
            {
                return "申请退款失败，订单当前状态不允许退款操作";
            }

            if (dsOrder.Tables[0].Rows[0]["ORDER_BUYER_ID"].ToString() != msBsc.SvRef.UserInfo.Operator)
            {
                return "申请退款失败，当前登录账号与下单信息不一致";
            }

            DataSet dsCurrentCharge = new CBizDjkChargeTradingLog().GetTradingLogByOrderId(orderId);
            if (dsCurrentCharge == null
                || dsCurrentCharge.Tables[0].Rows.Count <= 0)
            {
                return "申请退款失败，当前订单不存在交易记录";
            }
            if (dsCurrentCharge.Tables[0].Rows[0]["TRADING_SID"].ToString() != "已支付")
            {
                return "申请退款失败，当前订单尚未成功支付";
            }

            DataSet dsCurrentRefund = GetRefundInfoByOrderId(orderId);
            if (dsCurrentRefund.Tables[0].Rows.Count == 1
                && (RefundStatus)dsCurrentRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] != RefundStatus.CancelRefund
                && (RefundStatus)dsCurrentRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] != RefundStatus.DenyRefund)
            {
                return "申请退款失败，当前订单已有生效中的退款记录";
            }

            DataSet dsRefund = new CDmDjkCustomerRefund();
            DataRow dr = dsRefund.Tables[0].NewRow();
            //事物处理
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                //如果订单 在  服务开始时间 15天外就直接退款
                DateTime createTime = Convert.ToDateTime(dsOrder.Tables[0].Rows[0]["ORDER_TIME"]);
                DateTime starTime = Convert.ToDateTime(dsOrder.Tables[0].Rows[0]["ORDER_START_TIME"]);
                bool isChecked = false;
                //十五天内 游客违约不能退款
                if (createTime.AddDays(15) > starTime && breachPerson == 2)
                {
                    return "15天以内不能退款";
                }
                else if (createTime.AddDays(15) < starTime)
                {
                    //十五天外游客违约 自动退款 发送消息
                    new CBizMessageSystem().AddMessage("[退款提示]你有一笔订单已自动退款。", string.Format("订单号为:{0}一笔订单在 15天以外，已自动退款&nbsp;&nbsp;<a class='nav-on' target='_blank' href='/ws_OrderInfo.htm?orderId={1}'>查看详情》</a>",
                        dsOrder.Tables[0].Rows[0]["ORDER_CODE"].ToString(),
                        dsOrder.Tables[0].Rows[0]["ORDERS_INFO_ID"].ToString()),
                        dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"].ToString());

                    //修改状态
                    dr["REFUND_RECORD_STATUS"] = (int)RefundStatus.CheckedRefund;
                    dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.SurePayBack;

                    isChecked = true;
                }
                else
                {
                    dr["REFUND_RECORD_STATUS"] = (int)RefundStatus.ApplyRefund;
                    dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.ApplyPayBack;
                }
                dr["CUSTOMER_REFUND_ID"] = this.DataObj.NewID();
                dr["REFUND_ORDER_ID"] = orderId;
                dr["REFUND_COUNT"] = decimal.Parse(dsCurrentCharge.Tables[0].Rows[0]["TRADING_AMT"].ToString());
                dr["APPLY_REFUND_TIME"] = this.dtCurrDateTime;
                dr["REFUND_CUSTOMER_ID"] = msBsc.SvRef.UserInfo.Operator;
                dr["REFUND_DJACK_ID"] = dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"];

                dr["REFUND_RECORD_EXPANATION"] = expanation;
                dr["REFUND_DJACK_CHECK"] = 0;
                dr["REFUND_IS_FINISHED"] = 0;
                dr["REFUND_IS_DELETED"] = 0;
                dr["REFUND_IS_DISPLAY"] = 1;
                dr["BREACH_PERSON"] = breachPerson;
                dsRefund.Tables[0].Rows.Add(dr);

                objCBizOrdersInfo.Update(dsOrder);
                this.Update(dsRefund);

                //确认 后台  自动去退款
                if (isChecked)
                {
                    using (CBizDjkChargeTradingLog djkTrading = new CBizDjkChargeTradingLog())
                    {
                        string msg = djkTrading.RefundCust(orderId);
                        if (msg != "OK")
                        {
                            return msg;
                        }
                    }
                }

                ts.Complete();
            }
            return "OK";
        }

        /// <summary>
        /// 确认退款信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string CheckRefund(string orderId)
        {
            CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo();

            DataSet dsOrder = objCBizOrdersInfo.GetOrderInfoById(orderId);

            if (dsOrder == null || dsOrder.Tables[0].Rows.Count <= 0)
            {
                return "不存在该订单";
            }


            DataSet dsRefund = GetRefundInfoByOrderId(orderId);

            if (dsRefund == null
                || dsRefund.Tables[0].Rows.Count <= 0)
            {
                return "确认退款信息失败，该订单不存在退款申请";
            }
            if (dsRefund.Tables[0].Rows[0]["REFUND_DJACK_ID"].ToString() != msBsc.SvRef.UserInfo.Operator)
            {
                return "确认退款信息失败，订单号错误";
            }

            if ((RefundStatus)dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] != RefundStatus.ApplyRefund)
            {
                return "确认退款信息失败，退款申请当前状态不能进行确认";
            }

            dsRefund.Tables[0].Rows[0]["REFUND_DJACK_CHECK"] = 1;
            dsRefund.Tables[0].Rows[0]["REFUND_CHECK_TIME"] = this.dtCurrDateTime;
            dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] = (int)RefundStatus.CheckedRefund;
            dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.SurePayBack;
            //事物处理
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                objCBizOrdersInfo.Update(dsOrder);

                this.Update(dsRefund);
                //确认退款处理
                string msg = new CBizDjkChargeTradingLog().RefundCust(orderId);
                if (msg != "OK") { return msg; }

                //确认退款 消息处理
                new CBizMessageSystem().AddMessage("[退款提示]你有一笔订单已确认退款。", string.Format("订单号为:{0}一笔订单已确认退款&nbsp;&nbsp;<a class='nav-on' target='_blank' href='/ws_OrderInfo.htm?orderId={1}'>查看详情》</a>",
                       dsOrder.Tables[0].Rows[0]["ORDER_CODE"].ToString(),
                       dsOrder.Tables[0].Rows[0]["ORDERS_INFO_ID"].ToString()),
                       dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"].ToString());


                ts.Complete();
            }
            return "OK";
        }

        /// <summary>
        /// 取消退款信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string CancelRefund(string orderId)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "订单信息有误";
            }

            CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo();
            DataSet dsOrder = objCBizOrdersInfo.GetOrderInfoById(orderId);

            if (dsOrder == null || dsOrder.Tables[0].Rows.Count <= 0)
            {
                return "订单信息有误";
            }

            DataSet dsRefund = GetRefundInfoByOrderId(orderId);

            //验证订单是否存在
            if (dsRefund == null
                || dsRefund.Tables[0].Rows.Count <= 0)
            {
                return "该订单不存在该退款信息";
            }
            //验证订单 是否属于 该用户
            if (dsRefund.Tables[0].Rows[0]["REFUND_CUSTOMER_ID"].ToString() != msBsc.SvRef.UserInfo.Operator)
            {
                return "取消退款失败，订单号错误";
            }

            if ((RefundStatus)dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] != RefundStatus.ApplyRefund)
            {
                return "前状态不允许取消退款";
            }
            dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.RefundCanceled;
            dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] = (int)RefundStatus.CancelRefund;
            //事物处理
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                objCBizOrdersInfo.Update(dsOrder);
                this.Update(dsRefund);
                ts.Complete();
            }
            return "OK";
        }

        /// <summary>
        /// 拒绝退款
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string DenyRefund(string orderId, string refundExpanation)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "订单信息有误";
            }

            if (string.IsNullOrEmpty(refundExpanation))
            {
                return "请填写拒绝退款理由";
            }

            CBizOrdersInfo objCBizOrdersInfo = new CBizOrdersInfo();

            DataSet dsOrder = objCBizOrdersInfo.GetOrderInfoById(orderId);

            if (dsOrder == null
                || dsOrder.Tables[0].Rows.Count <= 0)
            {
                return "该订单不存在";
            }

            DataSet dsRefund = GetRefundInfoByOrderId(orderId);

            if (dsRefund == null
                || dsRefund.Tables[0].Rows.Count <= 0)
            {
                return "该订单不存在退款记录";
            }

            if ((RefundStatus)dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] != RefundStatus.ApplyRefund)
            {
                return "该订单当前状态不允许拒绝退款";
            }
            //验证订单 是否属于 该用户
            if (dsRefund.Tables[0].Rows[0]["REFUND_DJACK_ID"].ToString() != msBsc.SvRef.UserInfo.Operator)
            {
                return "拒绝退款失败，订单号错误";
            }
            dsOrder.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.Refusal;
            dsRefund.Tables[0].Rows[0]["REFUND_RECORD_STATUS"] = RefundStatus.DenyRefund;
            dsRefund.Tables[0].Rows[0]["REFUND_RMK"] = refundExpanation;
            //事物处理
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                objCBizOrdersInfo.Update(dsOrder);
                this.Update(dsRefund);
                ts.Complete();

                new CBizMessageSystem().AddMessage("[退款提示]你有一笔订单已被拒绝退款。", string.Format("订单号为:{0}一笔订单已被拒绝推荐&nbsp;&nbsp;<a class='nav-on' target='_blank' href='/ws_OrderInfo.htm?orderId={1}'>查看详情》</a>",
                       dsOrder.Tables[0].Rows[0]["ORDER_CODE"].ToString(),
                       dsOrder.Tables[0].Rows[0]["ORDERS_INFO_ID"].ToString()),
                       dsOrder.Tables[0].Rows[0]["ORDER_SOLDER_ID"].ToString());
            }
            return "OK";
        }

        /// <summary>
        /// 查询退款详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public DataSet GetRefundInfoByOrderId(string orderId)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT TOP 1 * FROM DJK_CUSTOMER_REFUND WHERE REFUND_ORDER_ID=@orderId ORDER BY APPLY_REFUND_TIME DESC", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }
    }

    /// <summary>
    /// 退款枚举
    /// </summary>
    public enum RefundStatus
    {
        /// <summary>
        /// 全部退款信息
        /// </summary>
        AllRefund = 0,
        /// <summary>
        /// 申请退款中
        /// </summary>
        ApplyRefund = 1,
        /// <summary>
        /// 确认退款
        /// </summary>
        CheckedRefund = 2,
        /// <summary>
        /// 退款已拒绝
        /// </summary>
        DenyRefund = 3,
        /// <summary>
        /// 退款已取消
        /// </summary>
        CancelRefund = 4,
        /// <summary>
        /// 退款已完成
        /// </summary>
        Finished = 5
    }
}
